const codeRecord = require("../models/codeRecord")
const user = require("../models/userDetail")
const point = require("../models/point")
const menu = require("../models/menu")
const code = require("../models/code")

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            user.find({
                // flags: {
                //     $all: fields.flags
                // }
            }, {
                UUID: 1,
                realName: 1
            }, (err, docs) => {
                // console.log("1: " + docs.length)
                if (err) {
                    res.json({ 'state': false, 'msg': err });
                } else {
                    if (docs.length == 0) {
                        res.json({
                            state: true,
                            coding_list: []
                        });
                    } else if (docs.length != 0) {
                        let uuid_list = docs.map((ele) => {
                            return ele.UUID
                        })
                        // console.log("uuid_list: " + uuid_list.length)

                        codeRecord.aggregate([
                            { $unwind: '$codeRecord_list' },
                            { $match: { 'codeRecord_list.content.user': { $in: uuid_list } } },
                        ], (err, results) => {
                            // console.log("2: " + results.length + JSON.stringify(results[0]) + JSON.stringify(results[1]))
                            if (err) {
                                res.json({ 'state': false, 'msg': err })
                            } else {
                                let coding_list = []
                                let coding_list_point = []
                                let temp_book = {}
                                let points_list = {}
                                let demos_list = {}
                                let pointId_list = []
                                let demoId_list = []

                                let group_by_person = () => {
                                    return new Promise(function (resolve, reject) {
                                        results.forEach((ele) => {
                                            let userUUID = ele.codeRecord_list.content.user
                                            if(ele.codeRecord_list.content.pointId!==undefined&&ele.codeRecord_list.content.pointId!==""){
                                                pointId_list.push(ele.codeRecord_list.content.pointId)
                                            } else if(ele.codeRecord_list.content.demoId!==undefined&&ele.codeRecord_list.content.demoId!==""){
                                                demoId_list.push(ele.codeRecord_list.content.demoId)
                                            }
                                            // console.log(ele.codeRecord_list.content.demoId)
                                            if (temp_book[userUUID] == undefined) {
                                                coding_list.push([ele.codeRecord_list])
                                                temp_book[userUUID] = coding_list.length - 1
                                                coding_list_point[temp_book[userUUID]] = []
                                            } else {
                                                coding_list[temp_book[userUUID]].push(ele.codeRecord_list)
                                            }
                                        })
                                        // console.log("group_by_person: " + coding_list.length)
                                        resolve()
                                    })
                                }

                                let find_pointAndDemo = () => {
                                    return new Promise(async function (resolve, reject) {
                                    //     point.find({
                                    //         _id: {
                                    //             $in: pointId_list
                                    //         }
                                    //     },{
                                    //         menu: 1,
                                    //         title: 1
                                    //     },(err, points) => {
                                    //         if(err) {
                                    //             res.json({ 'state': false, 'msg': err })
                                    //         } else {
                                    //             resolve(points)
                                    //         }
                                    //     })
                                        let points = await point.find({
                                            _id: {
                                                $in: pointId_list
                                            }
                                        },{
                                            menu: 1,
                                            title: 1
                                        })
                                        let demos = await code.find({
                                            _id: {
                                                $in: demoId_list
                                            }
                                        },{
                                            name: 1
                                        })
                                        demos.forEach(ele => {
                                            demos_list[ele._id] = ele.name
                                        })
                                        // console.log(demos_list)
                                        resolve(points) 
                                    })
                                }

                                let find_mune = (points) => {
                                    return new Promise(function (resolve, reject) {
                                        menu.find({},(err, menus) => {
                                            if(err) {
                                                res.json({ 'state': false, 'msg': err })
                                            } else {
                                                points.forEach((ele) => {
                                                    let menu_point = ele.menu.split(",")
                                                    let m = menus.find((e) => {
                                                        return e.lesson === menu_point[0]
                                                    })
                                                    points_list[ele._id] = {}
                                                    points_list[ele._id].pointTitle = ele.title
                                                    points_list[ele._id].menuTitle = m.menu[menu_point[1]].title
                                                    points_list[ele._id].menuSubtitle = m.menu[menu_point[1]].subtitle[menu_point[2]]
                                                    // console.log(points_list)
                                                })
                                                // console.log(points_list)
                                                resolve()
                                            }
                                        })
                                    })
                                }

                                let group_by_pointAndDemo = () => {
                                    return new Promise(function (resolve, reject) {
                                        coding_list.forEach(element => {
                                            let userUUID = element[0].content.user
                                            let temp_book_point = {}
                                            let temp_book_demo = {}
                                            element.forEach(ele => {
                                                if(ele.content.pointId!==undefined&&ele.content.pointId!==""){
                                                    let pointId = ele.content.pointId
                                                    if(temp_book_point[pointId] == undefined) {
                                                        coding_list_point[temp_book[userUUID]].push([ele])
                                                        temp_book_point[pointId] = coding_list_point[temp_book[userUUID]].length - 1
                                                    } else {
                                                        coding_list_point[temp_book[userUUID]][temp_book_point[pointId]].push(ele)
                                                    }
                                                } else if (ele.content.demoId!==undefined&&ele.content.demoId!==""){
                                                    let demoId = ele.content.demoId
                                                    if(temp_book_demo[demoId] == undefined) {
                                                        coding_list_point[temp_book[userUUID]].push([ele])
                                                        temp_book_demo[demoId] = coding_list_point[temp_book[userUUID]].length - 1
                                                    } else {
                                                        coding_list_point[temp_book[userUUID]][temp_book_demo[demoId]].push(ele)
                                                    }
                                                }
                                            })
                                            
                                        });
                                        // console.log(coding_list_point[temp_book['2c504ee0-7878-11e9-807c-336fd6b34fc0']][coding_list_point[temp_book['2c504ee0-7878-11e9-807c-336fd6b34fc0']].length-1])
                                        resolve()
                                    })
                                }

                                let sort_by_person = () => {
                                    return new Promise(function (resolve, reject) {
                                        coding_list_point.forEach((student_records) => {
                                            student_records.forEach((ele) => {
                                                ele.sort(function (a, b) {
                                                    return a.content.time - b.content.time
                                                })
                                            })
                                        })
                                        resolve()
                                    })
                                }

                                let return_data = () => {
                                    let coding_list_temp = []
                                    let name = {}
                                    docs.forEach((ele) => {
                                        name[ele.UUID] = ele.realName
                                    })
                                    // console.log
                                    coding_list_point.forEach((student_records) => {
                                        student_records.forEach((point_records) => {
                                            //某个学生的 某一知识点或案例 的记录
                                            let total_time = 0
                                            let last_startTime = 0
                                            let time_space = 0
                                            point_records.forEach((e) => {
                                                if(e.content.startTime===last_startTime||last_startTime===0){
                                                    time_space = e.content.time - e.content.startTime
                                                    if(e.type=="ONLINE_CODING_LEAVETIME") {
                                                        time_space = e.content.leaveTime - e.content.startTime
                                                    }
                                                } else {
                                                    total_time = total_time + time_space
                                                    time_space = 0
                                                }
                                                last_startTime = e.content.startTime
                                                // if(e.type=="ONLINE_CODING_LEAVETIME") {
                                                //     total_time = total_time + e.content.leaveTime - e.content.startTime
                                                // }
                                            })
                                            total_time = total_time + time_space
                                            // console.log(total_time)
                                            let length = point_records.length

                                            let stu_point_item = {
                                                name: name[point_records[0].content.user],
                                                submit_num: 0,
                                                point: "",
                                                menu: "",
                                                total_time: parseFloat((total_time / (1000 * 60)).toFixed(1)),
                                                topInterval: 0
                                            }
                                            if(point_records[0].content.pointId!==undefined&&point_records[0].content.pointId!==""){
                                                stu_point_item.point = points_list[point_records[0].content.pointId].pointTitle
                                                stu_point_item.menu = "<p>" + points_list[point_records[0].content.pointId].menuTitle + "</p><p>" + points_list[point_records[0].content.pointId].menuSubtitle + "</p>"
                                            } else if(point_records[0].content.demoId!==undefined&&point_records[0].content.demoId!==""){
                                                // console.log(demos_list[point_records[0].content.demoId])
                                                if(demos_list[point_records[0].content.demoId]===undefined){
                                                    return
                                                }
                                                stu_point_item.point = demos_list[point_records[0].content.demoId]
                                                stu_point_item.menu = "<strong>案例实践</strong>"
                                            }
                                            
                                            if (point_records[0].type == "ONLINE_CODING_SUBMIT") stu_point_item.submit_num = 1
                                            for (let i = 1; i < length; i++) {
                                                if (point_records[i].type == "ONLINE_CODING_SUBMIT") stu_point_item.submit_num++
    
                                                let new_interval = 0
                                                if(point_records[i-1].content.time > point_records[i].content.startTime) {
                                                    new_interval = ((point_records[i].content.time - point_records[i - 1].content.time) / (1000 * 60)).toFixed(1)
                                                }
                                                if (new_interval > stu_point_item.topInterval) stu_point_item.topInterval = new_interval
                                            }
                                            coding_list_temp.push(stu_point_item)
                                        })
                                    })
                                    // console.log("coding_list_temp" + coding_list_temp.length)
                                    // console.log(coding_list_temp)
                                    res.json({ 'state': true, 'data': coding_list_temp });
                                }

                                group_by_person().then(find_pointAndDemo).then(find_mune).then(group_by_pointAndDemo).then(sort_by_person).then(return_data)

                            }
                        })
                    }
                }
            })

        }

    });

});

module.exports = router;